package com.damai.mvc.view.imple;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.citywithincity.api.ApiConfig;
import com.citywithincity.utils.ClassUtil;
import com.citywithincity.utils.JsonUtil;
import com.damai.action.IAction;
import com.damai.action.IRender;
import com.damai.action.json.impl.SignUtil;
import com.damai.error.ErrorUtil;
import com.damai.utils.BeanUtils;

public class MchJsonRender implements IRender<Object> {
	public static final IRender<Object> DEFAULT = new MchJsonRender();
	@SuppressWarnings("unchecked")
	@Override
	public void render(IAction action, Object data, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		TreeMap<String, Object> treeMap = new TreeMap<String, Object>();
		treeMap.put("flag", 0);
		if(data instanceof Map){
			treeMap.putAll( (Map<String, Object>) data);
		}else{
			if(data == null || ClassUtil.isSimple(data.getClass()) || Collection.class.isAssignableFrom(data.getClass())){
				treeMap.put("result", data);
			}else{
				try {
					treeMap.putAll(BeanUtils.beanToMap(data));
				} catch (Exception e) {
					throw ErrorUtil.wrapThrow(e);
				}
			}
		}
		
		String mchId = (String) request.getAttribute("_mchId");
		String key = (String) request.getAttribute("_mchKey");
		treeMap = SignUtil.prepareData(treeMap, mchId, key);
		String value = JsonUtil.toJson(treeMap);
		if(ApiConfig.out){
			ApiConfig.info(value);
		}
		response.getWriter().print(value);
	}

}
